package com.atguigu.springcloud.contorller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.atguigu.springcloud.entity.CommonResult;
import com.atguigu.springcloud.entity.Payment;
import com.atguigu.springcloud.service.OrderService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class OrderController {
    public static final String SERVER_URL = "http://sentinel-payment-provider";
    private RestTemplate restTemplate;
    private OrderService orderService;

//    public OrderController(RestTemplate restTemplate) {
//        this.restTemplate = restTemplate;
//    }


    public OrderController(RestTemplate restTemplate, OrderService orderService) {
        this.restTemplate = restTemplate;
        this.orderService = orderService;
    }

    @GetMapping("/consumer/fallback/{id}")
//    @SentinelResource("fallback")
    @SentinelResource(value = "fallback", fallback = "fallbackHandler")
    public CommonResult<Payment> fallback(@PathVariable("id") Long id) {
        CommonResult<Payment> result = restTemplate.getForObject(SERVER_URL + "/paymentSQL/" + id, CommonResult.class, id);
        if (id == 4) {
            throw new IllegalArgumentException("非法参数异常");
        } else if (result.getData() == null){
            throw new NullPointerException("空指针异常");
        }
        return result;
    }

    public CommonResult<Payment> fallbackHandler(Long id, Throwable e) {
        Payment payment = new Payment(id, "null");
        return new CommonResult<>(444, "fallbackHandler" + e.getMessage(), payment);
    }

    @GetMapping("/consumer/paymentSQL/{id}")
    public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id) {
        return orderService.paymentSQL(id);
    }
}
